<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <!-- 固定显示首页，可点击 -->
    <el-breadcrumb-item :to="{ path: '/' }">主页</el-breadcrumb-item>
    <!-- 动态生成其他路径，不可点击 -->
    <template v-for="(item, index) in breadcrumbList" :key="index">
      <el-breadcrumb-item v-if="item.path != '/index'" :class="{ 'no-redirect': true }">
        {{ item.title }}
      </el-breadcrumb-item>
    </template>
  </el-breadcrumb>
</template>

<script setup lang="ts">
import type { SidebarMenu } from '@/types/router'
import useAuthStore from '@/stores/modules/auth'

const route = useRoute()
const authStore = useAuthStore()

// 递归查找菜单项
const findMenuByPath = (menuList: SidebarMenu[], targetPath: string): SidebarMenu | null => {
  for (const menu of menuList) {
    if (menu.path === targetPath) {
      return menu
    }
    if (menu.children && menu.children.length > 0) {
      const found = findMenuByPath(menu.children, targetPath)
      if (found) {
        return found
      }
    }
  }
  return null
}

// 生成面包屑列表
const breadcrumbList = computed(() => {
  const path = route.path
  if (path === '/') {
    return []
  }

  // 分割路径，生成路径数组
  // 例如：/system/user -> ['/system', '/system/user']
  const pathSegments = path.split('/').filter(Boolean)
  const paths: string[] = []

  pathSegments.forEach((segment, index) => {
    if (index === 0) {
      paths.push(`/${segment}`)
    } else {
      paths.push(`${paths[index - 1]}/${segment}`)
    }
  })

  // 获取recursiveMenuList
  const recursiveMenuList = authStore.getRecursiveMenuList
  const menuMetaMap = authStore.getMenuMetaMap
  const currentPath = route.path

  const list = paths.map((pathItem, index) => {
    const isLastPath = index === paths.length - 1 && pathItem === currentPath

    // 如果是最终路径，从recursiveMenuList中查找
    if (isLastPath) {
      const menuItem = findMenuByPath(recursiveMenuList, pathItem)
      if (menuItem && menuItem.meta?.title) {
        return {
          path: pathItem,
          title: menuItem.meta.title,
        }
      }
    }

    // 其他路径从menuMetaMap获取
    const meta = menuMetaMap.get(pathItem)
    return {
      path: pathItem,
      title: meta?.title || pathItem.split('/').pop() || pathItem,
    }
  })

  return list
})
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
